# src/service/artwork_service.py
from src.db.artwork_db import create_artwork, get_all_artworks, get_artwork_by_id
from src.db.user_db import get_user_by_id
from src.utils.logger import get_logger

logger = get_logger(__name__)

def publish_artwork(
    title: str,
    description: str,
    price: float,
    creator: str,
    owner_id: int,
    category: str = "",
    era: str = ""
) -> tuple[int | None, str]:
    """
    发布艺术品业务逻辑（校验卖家身份）
    返回：(艺术品ID/None, 提示信息)
    """
    # 1. 校验参数
    if not all([title, price, creator, owner_id]):
        logger.warning("发布艺术品参数缺失")
        return None, "缺少必填字段（标题、价格、创作者、卖家ID）"
    
    if price <= 0:
        logger.warning(f"艺术品价格无效（owner_id: {owner_id}, price: {price}）")
        return None, "价格必须大于0"
    
    # 2. 校验卖家身份（必须是"卖家"角色）
    seller = get_user_by_id(owner_id)
    if not seller or seller["user_role"] != "卖家":
        logger.warning(f"卖家身份无效（owner_id: {owner_id}）")
        return None, "仅卖家可发布艺术品"
    
    # 3. 创建艺术品
    artwork_id = create_artwork(
        title=title,
        description=description,
        price=price,
        creator=creator,
        owner_id=owner_id,
        category=category,
        era=era
    )
    
    if artwork_id:
        return artwork_id, "艺术品发布成功"
    else:
        return None, "艺术品发布失败"

def get_artwork_list(
    category: str = None,
    era: str = None,
    keyword: str = None
) -> list:
    """获取艺术品列表（支持筛选）"""
    artworks = get_all_artworks(category=category, era=era, keyword=keyword)
    # 可在此处添加额外业务处理（如：隐藏下架艺术品）
    return [art for art in artworks if art.get("status", "上架") == "上架"]

def get_artwork_detail(artwork_id: int) -> tuple[dict | None, str]:
    """获取艺术品详情（校验合法性）"""
    if not isinstance(artwork_id, int) or artwork_id <= 0:
        logger.warning(f"艺术品ID无效（artwork_id: {artwork_id}）")
        return None, "艺术品ID无效"
    
    artwork = get_artwork_by_id(artwork_id)
    if not artwork:
        return None, "艺术品不存在或已下架"
    
    # 补充卖家信息（隐藏卖家敏感字段）
    seller = get_user_by_id(artwork["owner_id"])
    if seller:
        artwork["seller_info"] = {
            "username": seller["username"],
            "real_name": seller["real_name"],
            "contact_info": seller["contact_info"]  # 实际项目需脱敏（如：138****5678）
        }
    
    return artwork, "获取详情成功"